$m(function(args){
	var $this = this.element;
	var cache = {};
	var form = $('#tempo-mgmt-property-form');
	var startTime = form.find('#startTime');
	var endTime = form.find('#endTime');
	var reset = $(".tempo-alg-reset-button").bind("click",function(){
		resetAll();
	});
	var search = $(".tempo-alg-search-button").bind("click",function(){
		getFilterData();
	});
	
	var data_load="";
    
	form.find("select[name=type]").selectmenu();
	form.find("select[name=status]").selectmenu();
	
	// 渲染开始日期
	var renderstartTime = function() {
		startTime.datepicker({
			dateFormat : "yy-mm-dd",
			yearRange : "c-100:",
			// 设置日期的最大时间和最小时间
			minDate : DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
			maxDate : DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
			changeYear : true,
			changeMonth : true,
			onChangeMonthYear : function(year, month, inst){ 
				var month = inst.selectedMonth + 1;
				var day = inst.selectedDay;
				var format = function(v) { return String(v).length > 1 ? v : ('0' + v) }
				$(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
			}
		});
	}
	// 渲染结束日期
	var renderendTime = function() {
		endTime.datepicker({
			dateFormat : "yy-mm-dd",
			yearRange : "c-100:",
			// 设置日期的最大时间和最小时间
			minDate : DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
			maxDate : DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
			changeYear : true,
			changeMonth : true,
			onChangeMonthYear : function(year, month, inst){ 
				var month = inst.selectedMonth + 1;
				var day = inst.selectedDay;
				var format = function(v) { return String(v).length > 1 ? v : ('0' + v) }
				$(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
			}
		});
	}
	
	/**
	 * 初始化组件
	 */
	var init = function(){
		$this.parent().find('.tempo-mgmt-tab').layout({
			north: {
				resizable : false,
				size : 50,
				spacing_open: 0
			}
		});
		renderstartTime();// 开始日期
		renderendTime();// 结束日期
	}

	
	/**
	 * 信息过滤
	 */
	var dataFilter=function(d,filterData){
		
		if(filterData==""){
			return true;
		}
		
		//状态
		if(filterData.status!="" && d.status!=filterData.status){
			return false;
		}
		
		//类型
		if(filterData.type!="" &&　d.lang.toUpperCase()!=filterData.type){
			return false;
		}
		
		//名称
		if(filterData.name!="" &&　d.name.toUpperCase().indexOf(filterData.name.toUpperCase())==-1){
			return false;
		}
		
		//用户名称
		if(filterData.username!="" &&　d.userName.indexOf(filterData.username)==-1){
			return false;
		}
		
		//创建时间
		var date=d.createDate;
		if(filterData.startTime!="" || filterData.endTime!=""){
			if(DateUtils.formatDateTime(date,"yyyy-MM-dd") != filterData.startTime && DateUtils.formatDateTime(date,"yyyy-MM-dd") != filterData.endTime ){
				if(filterData.startTime!=""){
					var s=new Date(Date.parse(filterData.startTime));
					if(date<s.getTime()){
						return false;
					}
				}
				if(filterData.endTime!=""){
					var s=new Date(Date.parse(filterData.endTime));
					if(date>s.getTime()){
						return false;
					}
				}
			}
		}
		
		return true;
	}
	

	/**
	 * 获取过滤值数据,并进行查询
	 */
	var getFilterData = function(){
		grid.clearGridData();
		//不符合条件，则从表单中移除
		var filterData = TempoUtils.getRecord(form);
		
		//结束时间不可早于起始时间
		if(filterData.startTime!=""&&filterData.endTime!=""){
			var s=new Date(Date.parse(filterData.startTime));
			var e=new Date(Date.parse(filterData.endTime));
			if(s>e){
				TempoUtils.showTip(TempoUtils.locale("mine.dateerrortip"));
			}
		}
		reloaddata(filterData);
	}
	
	/**
	 * 重置查询
	 */
	var resetAll = function(){
		//表单置空
		form.find("input[name='name']").val("");
		form.find("input[name='username']").val("");
		form.find('select[name="status"]').val("");
		form.find('select[name="type"]').val("");
		form.find("input[name='startTime']").val("");
		form.find("input[name='endTime']").val("");
		
		//清空重置
		grid.clearGridData();
		reloaddata("");
	}
	
	var reloaddata=function(filterData){
		$.post(contextPath + "/personal/listAllAlgorithm", function(data) {
			data_load=data;
			for(i in data.rows) {
				d=data.rows[i];
				cache[d.id] = d;
				var gridData2 = [];
				var src = "";
				if(d.image) {
					src = contextPath + "/personal/image?src=" + d.image + "&baseResPath=" + d.baseResPath;
				} else if(d.icon) {
					src = "data:image/png;base64," + d.icon
				} else if(d.id) {
					src = contextPath + "/personal/image?id=" + d.id
				}
				
				//过滤数据
				if(dataFilter(d,filterData)){
					grid.addRowData(d.id,{
						id:d.id,
						algid:d.id,
						icon:src,
						name:d.name,
						userName:d.userName,
						status:d.status,
						type:d.lang,
						createDate:d.createDate,
						opts:d.id,
						opts2:d.id,
					});
				}

			}
			var id=grid.getGridParam().pager+"_center";
			if(grid.jqGrid("getRowData").length==0){
				$(id).hide();
			}else{
				$(id).show();
			}
			grid.trigger("reloadGrid");
		});
	}
	
	var initGrid = function(data){
		var gridData=[];
		for(i in data) {
			d=data[i];
			cache[d.id] = d;
			var src = "";
			if(d.image) {
				src = contextPath + "/personal/image?src=" + d.image + "&baseResPath=" + d.baseResPath;
			} else if(d.icon) {
				src = "data:image/png;base64," + d.icon
			} else if(d.id) {
				src = contextPath + "/personal/image?id=" + d.id
			}
			gridData.push({
				id:d.id,
				algid:d.id,
				icon:src,
				name:d.name,
				userName:d.userName,
				status:d.status,
				type:d.lang,
				createDate:d.createDate,
				opts:d.id,
				opts2:d.id,
			});
		}
		
		var colName = ["",TempoUtils.locale("mine.icon"),TempoUtils.locale("mine.suanfamingcheng2"),TempoUtils.locale("mine.shenqingren2"),TempoUtils.locale("mine.publish_status"),TempoUtils.locale("mine.mine_type"),TempoUtils.locale("mine.publish-all-flow-grid-column-createtime"),TempoUtils.locale("mine.chakanxiangqin"),TempoUtils.locale("mine.publish-grid-column-opt")];
		var colModel = [{name: "algid",sortable:false,hidden : true},
		                {name: "icon",
						 align:"center",
						 sortable:false,
						 formatter : function(cellvalue) {return "<img src='"+cellvalue+"'></img>"},
						},
		                {name: "name", align:"center",sortable:false},
		                {name: "userName",align:"center", sortable:false},
		                {name: "status",
		                 align:"center",
		                 sortable:false,
		                 formatter:function(cellvalue){
		                	if(cellvalue == 'on') {
		             			return TempoUtils.locale("mine.yifabu");
		             		} else if(cellvalue == 'off'){
		             			return TempoUtils.locale("mine.weifabu");
		             		} else {
		             			return TempoUtils.locale("mine.unkown");
		             		}
		                 },
		                },
		                {name: "type", align:"center",sortable:false},
		                {name: "createDate", 
		                 align:"center",
		                 sortable:false,
		                 formatter:function(cellvalue){
		                	 if(cellvalue){
		                		 return DateUtils.formatDateTime(cellvalue);
		                	 }
		                	 return cellvalue;
		                	 
		                 },
		                },{name: "opts", 
					         align:"center",
					         sortable:false,
					         formatter:function(cellvalue){
					        	 			var s=cache[cellvalue].status;
			                	
					        	 			return '<span id="seeMore" class="user-defined-edit-action ui-icon tempo-ui-icon tempo-ui-icon-textseek" title='+TempoUtils.locale("mine.chakanxiangqin")+' uda-id="'+cellvalue+'"></div>';
			                	
					         			}
			                },
						
						{name: "opts2", 
					         align:"center",
					         sortable:false,
					         formatter:function(cellvalue){
					        	var s=cache[cellvalue].status;
			                	if(s=='on'){
			                		return '<div class="tempo-button ui-button ui-corner-all ui-widget" role="button" id="button_optpublish" style="width: 90px;" uda-id="'+cellvalue+'">'+TempoUtils.locale("mine.quxiaofabu")+'</div>';
			                	}else{
			                		return '<div class="tempo-button ui-button ui-corner-all ui-widget" role="button" id="button_optpublish" style="width: 90px;" uda-id="'+cellvalue+'">'+TempoUtils.locale("mine.publish-all-flow-grid-optpublish")+'</div>';
			                	}
					         }
			                }];

		var div_width=$(".tempo-mgmt-tab").width()-20;
		var content=$(".user-defined-mgmt-list");
		grid = $("<table width='100%' height='100%'>").appendTo(content);
		grid.datagrid({
			   fit: true,
			    //是否分页
	     	   pagination:true,
	     	   // 是否显示当前条数，开启分页后生效，默认不显示
	     	   showPageRecords:true,
	           datatype: "local",
	           data:gridData,
	           colNames: colName,
	           colModel: colModel,
	           rownumbers : true,
	           multiselect:false,
	           shrinkToFit : true,
	           rowNum:20,
	           rowList:[10,20,30],
	           showRefreshBth:false,
	           onSelectRow : function(rowId){
	        	   
	           },
		});
		
		var id=grid.getGridParam().pager+"_center";
		if(grid.jqGrid("getRowData").length==0){
			$(id).hide();
		}else{
			$(id).show();
		}
		
		//查看全部按钮
		grid.on('click', '#seeMore', function(e) {
			var ui = $(this);
			var id = ui.attr('uda-id');
			detailView(id);
		});
		
		//绑定发布按钮
		grid.on('click', '#button_optpublish', function(e) {
			var ui = $(this);
			var id = ui.attr('uda-id');
			var txt=ui.html();
			if(txt==TempoUtils.locale("mine.publish-all-flow-grid-optpublish")){
				ui.html(TempoUtils.locale("mine.quxiaofabu"))
			}else{
				ui.html(TempoUtils.locale("mine.publish-all-flow-grid-optpublish"))
			}
			
			operate(id);
		});
	}

	
	/**
	 * 算法详细信息
	 */
	var detailView = function(id) {
		var data = cache[id];
		dialog = $('.user-defined-edit-dailog').dialog({
			modal : true,
			autoOpen : false,
			width : 400,
			height : 540,
			title : data.name,
			resizable : false,
			close : function() {
				$('.user-defined-upload input').upload('destroy');
				$('.user-defined-upload').empty();
				$('.user-defined-edit-dailog').dialog('destroy');
			},
			open : function() {
				initForm(data, true);
			},
			buttons:[]
		}).dialog("open");
	}
	
	var initForm = function(data, full) {
		$('.user-defined-algorithm-info .text-value').empty();
		$('.user-defined-upload-form').remove();
		if(data) {
			var panel = $('.user-defined-algorithm-info');
			panel.find('.name').text(data.name || '');
			try{
				var v = TempoUtils.locale("mine." + data.subType);
				panel.find('.category').text(v);
			}catch(e){}
			panel.find('.lang').text(data.lang || '');
			panel.find('.username').text(data.userName || '');
			var d = DateUtils.formatDate(data.createDate);
			panel.find('.date').text(data.date || d || '');
			$('<textarea>').text(data.remark || '')
				.attr('readonly', true)
				.attr('title', data.remark || '')
				.appendTo(panel.find('.description'))
			var src = "";
			if(data.image) {
				src = contextPath + "/personal/image?src=" + data.image + "&baseResPath=" + data.baseResPath;
			} else if(data.icon) {
				src = "data:image/png;base64," + data.icon
			} else if(data.id) {
				src = contextPath + "/personal/image?id=" + data.id
			}
			$('<img>').attr('src', src).appendTo(panel.find('.image'));
			
		}
		$('.user-defined-algorithm-info textarea').css('height', '150px');
	}
	
	var operate = function(id) {
		var data = cache[id];
		var process = $("<div/>").tempoprogressbar();
		$.post(contextPath + '/personal/publish', {id: id}, function(d) {
			process.tempoprogressbar('destroy');
			if(d) {
				$('<div>').alert({
					msg: TempoUtils.locale("mine.caozuochenggong")
				});
				
				data.status = data.status == 'off' ? 'on' : 'off';
				//表格修改
				grid.setRowData(id,{status:data.status});
				//缓存数据修改
				cache[id].status=data.status;
				$.post(contextPath + "/personal/listAllAlgorithm", function(data) {
					data_load=data;
				});
				
			} else {
				$('<div>').alert({
					msg: TempoUtils.locale("mine.caozuoshibai")
				});
			}
		});
	}
	
	var loadList = function() {
		$.post(contextPath + "/personal/listAllAlgorithm", function(data) {
			data_load=data;
			initGrid(data.rows);
		});	
	}
	
	!function(){
		init();
		loadList();
		$(".tempo-mgmt-tab").parent().css("overflow","hidden")
	}();
});